 #include <iostream>
 #include <pthread.h>
 #include <string>
 #include <unistd.h>

pthread_mutex_t mtx;//定义一把锁
pthread_cond_t cond;//定义条件变量

void* ctrl(void* args)
{
    std::string name = (char*)args;
    while(true)
    {
        //唤醒在条件变量下的一个线程
        //在cond 等待队列里的第一个线程
        //pthread_cond_signal(&cond);
        std::cout << "master say: begin work" << std::endl; 
        pthread_cond_broadcast(&cond);//一次唤醒队列里的所有线程
        sleep(1);
    }
}

void* work(void* args)
{
    int number = *(int*)args;
    delete (int*)args;
    while(true)
    {
        pthread_cond_wait(&cond, &mtx);//等待条件就绪
        std::cout << "work: " << number << " is working..." << std::endl;;
    }
}

 int main()
 {
#define NUM 3
    pthread_mutex_init(&mtx, nullptr);//初始化锁
    pthread_cond_init(&cond, nullptr);//初始化条件变量

    pthread_t master;
    pthread_t worker[NUM];

    //创建线程
    pthread_create(&master, nullptr, ctrl, (void*)"master");
    for(int i = 0; i < NUM; ++i)
    {
        int* number = new int(i);
        pthread_create(worker+i, nullptr, work, number);
    }

    //等待线程
    pthread_join(master, nullptr);
    for(int i = 0; i < NUM; ++i)
    {
        pthread_join(worker[i], nullptr);
    }

    pthread_mutex_destroy(&mtx);//销毁锁
    pthread_cond_destroy(&cond);//销毁条件变量
    return 0;
 }